package com.handydata.antifraud.listener;

import com.handydata.common.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import com.handydata.antifraud.common.constant.AlarmInfoCode;
import com.handydata.antifraud.service.AlarmInfoService;

/**
 * @author lsm
 */
@Component
public class RedisExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AlarmInfoService alarmInfoService;
    private Logger logger = LoggerFactory.getLogger(RedisExpiredListener.class);

    public RedisExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     *监听redis key过期事件，发送超时预警
     */
    @Override
    public void onMessage(Message message, byte[] bytes) {
        String key=null;
        try{
            key=message.toString();

//            logger.info("开始接受超时key："+key);

            if(key==null||!key.startsWith(AlarmInfoCode.REDIS_ALARM_WACTH.getCode()))return;//其他的key过滤掉

            logger.info("开始处理超时key："+key);

            String[] strs=key.toString().split("_");
            String alarmItem=strs[1];
            String orderId=strs[2];
            String code=strs[3];

            alarmInfoService.sendWatchAbNormal(alarmItem,orderId,code,AlarmInfoCode.ALARM_TYPE_TIMEOUT.getCode(),"计算超时",null);

            logger.info("处理超时key完成："+key);

        }catch (Exception ex){
            logger.error("发送超时消息时出错key:"+key,ex);
        }

    }
}